package com.growthserver.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.github.pagehelper.PageHelper;
import com.growthserver.entity.IntegralBudgetEntity;
import com.growthserver.entity.TTaskAssignEntity;
import com.growthserver.entity.TTaskRuleDoRecordEntity;
import com.growthserver.entity.UserInfoEntity;
import com.growthserver.enums.ResultBeans;
import com.growthserver.excelFileEntity.IntegralBudgetExclEntity;
import com.growthserver.mapper.AppletMapper;
import com.growthserver.mapper.GrowthCenterMapper;
import com.growthserver.mapper.IntegralGrowthMapper;
import com.growthserver.param.GrowthParam;
import com.growthserver.param.IntegralBudgetParam;
import com.growthserver.service.GrowthCenterService;
import com.growthserver.util.ExclUtils;
import com.growthserver.vo.IntegralBudgetVo;
import com.growthserver.vo.TTaskAssignVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GrowthCenterServiceImpl implements GrowthCenterService {

    private final Logger LOGGER = LoggerFactory.getLogger(GrowthCenterService.class);

    @Autowired
    private GrowthCenterMapper growthCenterMapper;

    @Autowired
    private IntegralGrowthMapper integralGrowthMapper;
    /**
     *
     */
    @Autowired
    private AppletMapper appletMapper;

    @Value("${integralTimeRange}")
    private String integralTimeRange;



    /**
     * 发放积分成长值列表展示
     * @param growthParam
     * @return
     */
    @Override
    public List<TTaskAssignEntity> detailQuery(GrowthParam growthParam) {
        PageHelper.startPage(growthParam.pageNo, growthParam.pageSize);
        return growthCenterMapper.detailQuery(growthParam);
    }

    /**
     * 批量,单独发放积分,成长值
     * @param tTaskAssignVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBeans<Object> batchSingleSendSendSend(TTaskAssignVo tTaskAssignVo, MultipartFile file) {
        ResultBeans<Object>  result= new ResultBeans<>();
        boolean b = integralBudgetCheck(tTaskAssignVo.getDoType(),tTaskAssignVo.getRequestNum(), tTaskAssignVo.getIntegralValue());
        if(b){
            result.setResult("0");
            result.setMsg("预审编号校验:编号不存在,或者未审核通过请再次检查:{}"+tTaskAssignVo.getRequestNum());
            return result;
        }
        //更新积分预算单号使用
        appletMapper.updateIntegralBudgetIntegralValue(tTaskAssignVo.getRequestNum(), tTaskAssignVo.getIntegralValue());

        //设置list集合
        List<String> userIds = new ArrayList<>();
        if (file == null) {
            userIds.add(tTaskAssignVo.getUserId());
        } else {
            try {
                userIds = ExclUtils.getExclData(file);
            } catch (IOException e) {
                LOGGER.info("excl解析用户ID报错");
            }
        }
        // 获取所有会员ID
        List<String> strings = appletMapper.selectMember();
        boolean exists = new HashSet<>(strings).containsAll(userIds);
        if(!exists){
            //获取不存在的数据
            userIds.removeAll(strings);
            result.setResult("0");
            List<String> arrayList = new ArrayList<>();
            userIds.forEach(p->{p="用户ID不存在:"+p;arrayList.add(p);});
            result.setRows(arrayList);
            result.setMsg("数据库不存在数据");
            return result;
        }

        if (tTaskAssignVo.getTaskId() == null) {
            //添加积分,成长 明细表任务
            String taskId = String.valueOf(new Date().getTime());
            tTaskAssignVo.setTaskId(taskId);
        }
        //添加用户关联表 通过积分成长表ID,和user
        growthCenterMapper.batchOrSimpleSend(tTaskAssignVo);
        //积分有效期时长
        tTaskAssignVo.setIntegralTimeRange(integralTimeRange);
        growthCenterMapper.insetUserIntegral(userIds, tTaskAssignVo.getTaskId(),
                integralTimeRange,
                tTaskAssignVo.getCreator(),
                tTaskAssignVo.getCreatedName());
        //TODO 数据插入到 T_TASK_RULE_DO_RECORD
        TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = new TTaskRuleDoRecordEntity();
        tTaskRuleDoRecordEntity.setTaskRuleId("6");
        tTaskRuleDoRecordEntity.setTaskType("6");
        if ("1".equals(tTaskAssignVo.getOperateType())) {
            tTaskRuleDoRecordEntity.setActionType("13");
        } else {
            tTaskRuleDoRecordEntity.setActionType("14");
        }
        tTaskRuleDoRecordEntity.setIntegralType(tTaskAssignVo.getDoType());
        tTaskRuleDoRecordEntity.setIntegralValue(tTaskAssignVo.getIntegralValue());
        tTaskRuleDoRecordEntity.setGrowthValue(tTaskAssignVo.getGrowthValue());
        LocalDateTime localDateTime = LocalDateTime.now().plusYears(Integer.parseInt(integralTimeRange));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        tTaskRuleDoRecordEntity.setIntegralEndTime(dateTimeFormatter.format(localDateTime));
        for (String userId:userIds
             ) {
            tTaskRuleDoRecordEntity.setUserId(userId);
            tTaskRuleDoRecordEntity.setWeekEndTime("-1");
            tTaskRuleDoRecordEntity.setMonthEndTime("-1");
            tTaskRuleDoRecordEntity.setBudgetRequestNum(tTaskAssignVo.getRequestNum());
            tTaskRuleDoRecordEntity.setDepartment(tTaskAssignVo.getTaskDistributeDepartment());
            integralGrowthMapper.insertRuleLog(tTaskRuleDoRecordEntity);
        }
        result.setResult("1");
        result.setRows(new ArrayList<>());
        result.setMsg("积分批量发放成功");
        return result;
    }

    /**
     * 积分预算分值校验
     */
    private boolean integralBudgetCheck(String doType,String budgetRequestNum,String integralValue){
        //积分扣减 不关注 剩余积分.只关注预算积分单号是否存在
        if(doType.equals("0")){
            budgetRequestNum= "0";
        }
        String check = integralGrowthMapper.integralBudgetCheck(budgetRequestNum, integralValue);
        if(check != null && check.equals("1")){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 查看单个发布任务详情
     * @param growthParam
     * @return
     */
    @Override
    public List<HashMap<String, String>> queryMemberIds(GrowthParam growthParam) {
        return growthCenterMapper.queryMemberIds(growthParam.getTaskId());
    }

    /**
     * 根据ID删除特定发放任务
     * @param growthParam
     */
    @Override
    public void deleteById(GrowthParam growthParam) {
        growthCenterMapper.deleteById(growthParam.getTaskId());
    }

    @Override
    public List<UserInfoEntity> getUserInfo(GrowthParam growthParam) {
        PageHelper.startPage(growthParam.getPageNo(),growthParam.getPageSize());
       return growthCenterMapper.getUserInfo(growthParam);
    }

    /**
     * 任务枚举
     * @param growthParam
     * @return
     */
    @Override
    public List<HashMap<String,String>> taskTypeEnum(GrowthParam growthParam) {
        List<String> list = growthCenterMapper.taskTypeEnum(growthParam);
        List<HashMap<String,String>> arrayList = new ArrayList<>();
        for (String vaule:list
        ) {
            HashMap<String, String> map = new HashMap<>();
            String[] split = vaule.split(",");
            map.put("moduleType",split[0]);
            map.put("moduleName",split[1]);
            map.put("taskType",split[2]);
            map.put("taskName",split[3]);
            arrayList.add(map);
        }
        return arrayList;
    }





    /**
     * 积分预算申请列表展示
     * @param integralBudgetParams
     * @return
     */
    @Override
    public List<IntegralBudgetEntity> integralBudgetDisplay(IntegralBudgetParam integralBudgetParams) {
        PageHelper.startPage(integralBudgetParams.pageNo, integralBudgetParams.pageSize);
        return growthCenterMapper.queryIntegralBudget(integralBudgetParams);
    }

    /**
     * 积分预算创建
     * @param integralBudgetVo
     */
    @Override
    public void integralBudgetCreate(IntegralBudgetVo integralBudgetVo) {
        growthCenterMapper.integralBudgetCreate(integralBudgetVo);
    }

    /**
     * 积分预算审核
     * @param integralBudgetEntity
     */
    @Override
    public void integralBudgetAudit(IntegralBudgetEntity integralBudgetEntity){
        growthCenterMapper.integralBudgetAudit(integralBudgetEntity);
    }

    @Override
    public ResultBeans<Object> integralBudgetExcel(String userId, String userName, MultipartFile file) {
        ResultBeans<Object> result = new ResultBeans<>();
        List<IntegralBudgetExclEntity> integralBudgetExclData = new ArrayList<>();
        List<List<IntegralBudgetExclEntity>> list = new ArrayList<>();
        //file文件解析
        try {
            integralBudgetExclData = ExclUtils.getIntegralBudgetExclData(file);
        } catch (IOException e) {
            result.setResult("0");
            result.setRows("预审积分文件导入解析失败");
            return result;
        }
        if(integralBudgetExclData.isEmpty()){
            result.setResult("0");
            result.setRows("预审编号为空");
            return result;
        }
        integralBudgetExclData.forEach(p->{p.setCreator(userId);p.setCreatedName(userName);});
        if(integralBudgetExclData.size()>1000){
            List<List<IntegralBudgetExclEntity>> listIntegralBudgetExclEntity = ListUtil.split(integralBudgetExclData, 1000);
            listIntegralBudgetExclEntity.forEach(p->growthCenterMapper.integralBudgetExcel(p));
        }
        //查询 积分预审表中存在的预审编号
        List<String> strings = growthCenterMapper.selectIntegralBudgetNum();

        List<String> values = integralBudgetExclData.stream()
                .map(IntegralBudgetExclEntity::getIntegralBudgetNum)
                .collect(Collectors.toList());
        boolean exists = values.stream().anyMatch(strings::contains);
        if(exists){
            //获取存在的数据
            List<String> intersection = values.stream()
                    .filter(strings::contains)
                    .collect(Collectors.toList());
            result.setResult("0");
            List<String> arrayList = new ArrayList<>();
            intersection.forEach(p->{p="存在此预审编号:"+p;arrayList.add(p);});
            result.setRows(arrayList);
            result.setMsg("存在此预审编号");
            return result;
        }else {
            growthCenterMapper.integralBudgetExcel(integralBudgetExclData);
        }
        result.setResult("1");
        result.setRows(new ArrayList<>());
        result.setMsg("积分预算Excel导入成功");
        return result;
    }
}
